﻿using System.Collections.Generic;
using System.IO;
using Jayden.Dll.Web.Enums;

namespace Jayden.Dll.Web.Scripts
{
	public class JsFile
	{
		private List<string> m_Includes = new List<string>();
		private Dictionary<string, JsEntry> m_EntryByKey = new Dictionary<string, JsEntry>();
		private List<JsEntry> m_Entries = new List<JsEntry>();

		public bool Contains(string key) { return m_EntryByKey.ContainsKey(key); }

		public void Include(string filepath)
		{
			if (!m_Includes.Contains(filepath))
				m_Includes.Add(filepath);
		}
		public JsEntry this[string key]
		{
			get
			{
				JsEntry entry;
				if (!m_EntryByKey.TryGetValue(key, out entry))
				{
					entry = new JsEntry(key);
					m_EntryByKey.Add(key, entry);
					m_Entries.Add(entry);
				}
				return entry;
			}
		}

		public void Render(TextWriter writer, RenderMode mode)
		{
			foreach (string include in m_Includes)
			{
				if (mode == RenderMode.Debug)
				{
					writer.WriteLine();
					writer.WriteLine("/* Include '{0}' */", include);
				}
				writer.WriteLine(File.ReadAllText(include));
			}
			foreach (JsEntry entry in m_Entries)
			{
				if(entry.Builder.Length > 0)
				{
					if(mode == RenderMode.Debug)
					{
						writer.WriteLine();
						writer.WriteLine("/* Entry '{0}' */", entry.Key);
					}
					writer.WriteLine(entry.Builder.ToString());
				}
			}
		}
	}
}
